package com.geek.user.controller;

import com.geek.common.entity.UserVO;
import com.geek.common.utils.JwtUtils;
import com.geek.system.feignClient.SystemServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/userss")
public class UserController {

    @Autowired
    private SystemServiceFeignClient systemServiceFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/add")
    public String addUser(@RequestBody UserVO user) {
        return systemServiceFeignClient.addSystem(user);
    }

    @PostMapping("/login")
    public String loginUser() {
//        1 验证用户名密码
//        2 jwt生成token
        // 1. 创建一个Map对象，用于存放声明信息
        Map<String, String> claims = new HashMap<>();

        // 2. 向Map中添加自定义声明
        claims.put("userId", "123455");      // 用户ID
        claims.put("role", "admin");        // 用户角色
        claims.put("username", "john_doe"); // 用户名（可选声明）
        String token =  JwtUtils.generateToken(claims);
//        3 存储token到redis
//        4  返回token给用户
        redisTemplate.opsForValue().set("token", token, 60 * 60 * 24, TimeUnit.SECONDS);
        return token;
    }

    @GetMapping(value = "/validateToken")
    public String validateToken(String token) {
        if (JwtUtils.validateToken(token)) {
            System.out.println("Token 验证: " + JwtUtils.validateToken(token));
            return "Token is valid";
        } else return "Token is invalid";
    }

    //    @GetMapping(value = "/getClaim")
    //    public String getClaim(String token) {
    //        String claim = JwtUtils.getClaim(token, "userId");
    //        System.out.println("Claim: " + claim);
    //        return claim;
    //    }
    @GetMapping(value = "/getClaim")
    public String getClaim(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring("Bearer ".length());
            // 这里得到了token，后续可进行解析等操作，比如调用JwtUtils的方法
            // 假设JwtUtils是你之前定义的工具类
             String userId = JwtUtils.getClaim(token, "userId");
            return userId;
        }
        return "未获取到有效的Token";
    }
}
